<template>
  <ag-grid-vue
    style="width: 100%; height: 100%; border: 0px;"
    class="ag-theme-balham"
    :gridOptions="gridOptions"
    @grid-ready="onGridReady"
    :columnDefs="columnDefs"
    :defaultColDef="defaultColDef"
    :components="components"
    :debug="false"
    :rowBuffer="rowBuffer"
    :rowSelection="rowSelection"
    :suppressCellSelection="true"
    :rowModelType="rowModelType"
    :paginationPageSize="paginationPageSize"
    :cacheOverflowSize="cacheOverflowSize"
    :maxConcurrentDatasourceRequests="maxConcurrentDatasourceRequests"
    :infiniteInitialRowCount="infiniteInitialRowCount"
    :maxBlocksInCache="maxBlocksInCache"
    :frameworkComponents="frameworkComponents"
    :context="context"
    :checkboxSelection="true"
    :rowData="rowData"
    :localeText="localeText"
    :suppressContextMenu="suppressContextMenu"
  ></ag-grid-vue>
</template>

<script>
import sysApi from "@/api/sys";
import { AgGridVue } from "ag-grid-vue";
import CellButton from "./cellButton.js";
import language_ag from "../config/localization_ag";
import NotifyButton from "./notifyButton.js";

function createFlagImg(flag) {
  return (
    '<img border="0" width="15" height="10" src="https://flags.fmcdn.net/data/flags/mini/' +
    flag +
    '.png"/>'
  );
}

function CheckBoxRender(params) {
  var check = params.value == 1 ? " checked " : " ";
  return (
    '<div style="display: flex;justify-content: center;"><label><input name="Fruit" type="checkbox" ' +
    check +
    " disabled /></label></div>"
  );
}
/*根据value的值，来渲染单元格，value=1 折显示✔  否则什么都不显示*/
function StatusRender(params) {
  var flag = params.value == "已审批" ? "approval-pass" : "approval-wait";
  return (
    '<div style="display: flex;justify-content: center;" class="inTableBtn' +
    " " +
    flag +
    '" title="' +
    params.value +
    '"></div>'
  );
}
export default {
  name: "gridNoPage",
  props: {
    classId: {
      type: Number,
      default: 0
    },
    dataUrl: {
      type: String
    },
    httpMethod: {
      type: String
    },
    cellClick: {
      type: Function,
      default: null
    },
    selectionChange: {
      type: Function,
      default: null
    },
    cellDoubleClick: {
      type: Function,
      default: null
    },
    rowClick: {
      type: Function,
      default: null
    },
    rowDoubleClick: {
      type: Function,
      default: null
    },
    customButtonClick: {
      type: Function,
      default: null
    },
    notifyButtonClick: {
      type: Function,
      default: null
    },
    enableGridCheck: {
      type: Boolean,
      default: true
    },
    enableSerialNumber: {
      type: Boolean,
      default: true
    },
    customRender: {
      type: Function,
      default: null
    },
    customHeadName: {
      type: Array,
      default: () => []
    },
    getData: {
      type: Function,
      default: null
    },
    rowSelection: {
      type: String,
      default: 'multiple'
    },
    suppressContextMenu: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      columnDefs: [],
      rowData: [],
      gridOptions: null,
      gridApi: null,
      columnApi: null,
      components: null,
      rowBuffer: null,
      rowModelType: null,
      paginationPageSize: null,
      cacheOverflowSize: null,
      maxConcurrentDatasourceRequests: null,
      infiniteInitialRowCount: null,
      maxBlocksInCache: null,
      context: null,
      frameworkComponents: null,
      defaultColDef: null,
      localeText: language_ag
    };
  },
  components: {
    AgGridVue
  },
  async beforeMount() {
    const me = this;

    this.gridOptions = {};
    // this.rowModelType = "serverSide";
    this.cacheBlockSize = 100;
    this.maxBlocksInCache = 10;
    this.gridOptions.onCellClicked = this.cellClicked;
    this.gridOptions.onCellDoubleClicked = this.cellDoubleClicked;
    this.gridOptions.onRowClicked = this.rowClicked;
    this.gridOptions.onRowDoubleClicked = this.rowDoubleClicked;
    this.gridOptions.onSelectionChanged = this.selectionChanged;
    // 启动缓存快速查询，提高查询速度
    this.gridOptions.cacheQuickFilter = true;
    this.context = { componentParent: this };

    this.frameworkComponents = {
      cellButton: CellButton,
      notifyButton: NotifyButton
    };
    this.components = {
      // countryCellRenderer: CountryCellRenderer
      checkBoxRender: CheckBoxRender,
      customRender: this.customRender,
      statusRender: StatusRender
    };
    this.defaultColDef = {
      // headerCheckboxSelection: this.isFirstColumn,
      // checkboxSelection: this.isFirstColumn,
      editable: false,
      resizable: true,
      //单元格边框
      cellStyle: { "border-right": "1px solid #d9dcde" }
    };
    if (this.enableGridCheck) {
      this.defaultColDef.headerCheckboxSelection = this.isFirstColumn;
      this.defaultColDef.checkboxSelection = this.isFirstColumn;
    }

    // this.dataUrl = this.dataUrl;
    // this.httpMethod = this.httpMethod;

    if (this.classId > 0) {
      sysApi.getColumns({ classId: this.classId }).then(data => {
        if (data != null) {
          if (this.enableGridCheck) {
            me.columnDefs.push({
              headerName: "", //选择列头部显示的文字，可以为空
              checkboxSelection: true, //设置为true显示为复选框
              headerCheckboxSelection: true, //表头是否也显示复选框，全选反选用
              headerCheckboxSelectionFilteredOnly: true, // 设置为true时，当用filter过滤数据后，只会获取到过滤后的数据
              pinned: "left", //固定再左边
              width: 40 //列的宽度
            });
          }

          if (this.enableSerialNumber) {
            // 序号列
            this.columnDefs.push({
              headerName: "序号",
              field: "grid_serial",
              width: 50,
              pinned: "left",
              suppressMenu: true,
              valueGetter: params => {
                return (
                        params.node.rowIndex + 1
                );
              }
            });
          }

          if (data.result) {
            data.result.forEach((item, index) => {
              if (this.customHeadName && this.customHeadName[index]) {
                item.headerName = this.customHeadName[index];
              }
              me.columnDefs.push(item);
            });
          }
        }
      });
    }
  },
  mounted() {
    this.gridApi = this.gridOptions.api;
    this.gridColumnApi = this.gridOptions.columnApi;
  },
  /**
   *
   */
  methods: {
    isFirstColumn(params) {
      let displayedColumns = params.columnApi.getAllDisplayedColumns();
      let thisIsFirstColumn = displayedColumns[0] === params.column;
      return thisIsFirstColumn;
    },
    selectAll() {
      this.gridApi.selectAll();
    },
    deselectAll() {
      this.gridApi.deselectAll();
    },
    //获取选中的行，返回格式：[{},{}]

    /**
     * 获取被选择的行对象
     * @returns {[]}
     */
    getCheckeds() {
      let checkData = [];
      let nodes = this.gridApi.getSelectedNodes();
      nodes.forEach(node => {
        checkData.push(node.data);
      });
      return checkData;
    },
    /**
     * 获取被选择的行的ID
     * @returns {string}  id1,id2,id3...
     */
    getCheckedIds() {
      let ids = "";
      let nodes = this.gridApi.getSelectedNodes();
      nodes.forEach(node => {
        return (ids += node.data.userSerial + ",");
      });

      return ids.substring(0, ids.length - 1);
    },
    cellClicked(node) {
      if (this.cellClick) {
        this.cellClick(node);
      }
    },
    cellDoubleClicked(node) {
      if (this.cellDoubleClick) {
        this.cellDoubleClick(node);
      }
    },
    rowClicked(node) {
      if (this.rowClick) {
        this.rowClick(node);
      }
    },
    rowDoubleClicked(node) {
      if (this.rowDoubleClick) {
        this.rowDoubleClick(node);
      }
    },
    selectionChanged(node) {
      if (this.selectionChange) {
        this.selectionChange(node.api.getSelectedRows());
      }
    },
    onGridReady() {},
    async loadData(filter) {
      this.$loading("加载中...");
      if (filter) {
        this.rowData = [];
        const response = await sysApi.getData(
          this.dataUrl,
          this.httpMethod,
          filter
        );
        this.$loading.close();
        if (response && response.success) {
          this.rowData = response.result;
        } else {
          this.$messager.alert({
            title: "异常错误",
            icon: "error",
            msg: response.message
          });
        }
        this.gridApi.deselectAll();
      }
    },
    onCustomButtonClick(node) {
      if (this.customButtonClick) {
        this.customButtonClick(node);
      }
    },
    onNotifyButtonClick(node) {
      if (this.notifyButtonClick) {
        this.notifyButtonClick(node);
      }
    },
    test() {
      // console.log("测试------------");
      //
      // console.log(this.gridColumnApi.getColumn("userNo"));
      // console.log(this.columnDefs);
      // this.columnDefs[1].headerName = "abcd";
      // this.gridColumnApi.getColumn("userNo").colDef.headerName = "111";
      // this.gridColumnApi.resetColumnState();
    },
    /**
     * 根据ID重置表头
     * @param classId 字段描述ID
     */
    resetColumn(classId) {
      const me = this;
      sysApi.getColumns({ classId: classId }).then(data => {
        if (data != null) {
          me.columnDefs = data.result;
        }
      });

      this.gridColumnApi.resetColumnState();
    },
    /**
     * 重新设置表格列名
     * @param colName 列ID，字段名
     * @param headerName  列名称
     */
    setHeaderName(colName, headerName) {
      this.gridColumnApi.getColumn(colName).colDef.headerName = headerName;
    },
    /**
     * 刷新表格
     * 重新设置表格列名以后，要调用些方法刷新才生效
     */
    resetColumnState() {
      this.gridColumnApi.resetColumnState();
    },
    /**
     * 根据条件查询数据
     * @param value 查询条件
     */
    filterData(value) {
      this.gridApi.setQuickFilter(value);
    },
    /**
     * 插入数据
     * @param data  要插入的数据集合
     */
    add(data) {
      if (data) {
        if (data.add && data.add.length > 0) {
          this.gridApi.applyTransaction({add: data.add});
        }

        //TODO 更新有问题
        // if (data.update && data.update.length > 0) {
        //   console.log("更新的数据");
        //   console.log(data.update);
        //   data.update.forEach(row => {
        //     console.log("----node----");
        //     let n = this.gridApi.getRowNode(row.userSerial);
        //     console.log(n);
        //   })
        //   this.gridApi.applyTransaction({update: data.update});
        //   //
        //   // this.gridApi.applyTransaction({add: data.update});
        // }
      }
    },
    /**
     * 获取当前表格数据源
     * @returns {[]}
     */
    getGridData() {
      let dataList = [];
      this.gridApi.forEachNode(function(rowNode) {
        dataList.push(rowNode.data);
      });

      return dataList;
    },
    /**
     * 删除选中行
     */
    removeSelect() {
      let rows = this.gridApi.getSelectedRows();
      if (rows && rows.length > 0) {
        this.gridApi.applyTransaction({remove: rows});
      }
    },
    /**
     * 加班静态数据
     * @param dataList
     */
    loadList(dataList) {
      if (dataList) {
        this.rowData = dataList;
      }
    }
  }
};
</script>
<style>
/* ag-grid表格居中显示 */
.ag-theme-balham .ag-cell-value {
  text-align: center;
}
.ag-theme-balham .ag-cell-wrapper {
  justify-content: center;
}
.ag-theme-balham .ag-ltr .ag-row-drag,
.ag-theme-balham .ag-ltr .ag-selection-checkbox,
.ag-theme-balham .ag-ltr .ag-group-expanded,
.ag-theme-balham .ag-ltr .ag-group-contracted {
  margin-right: 0;
}

.ag-theme-balham .ag-root-wrapper {
  border: solid 0px;
  border-color: #bdc3c7;
  border-radius: 2px;
}

</style>
